# -*- coding: UTF-8 -*-
from django import template
from django.template import Node, NodeList, Template, Context, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END
 
register = template.Library()

#自定义filter
def id(value, arg=None):
    if value:
        return value.key()
    else:
        return ''

def count(value, arg=None):
    if value:
        return value.count()
    else:
        return 0

id.is_safe = False
count.is_safe = False

register.filter(id)
register.filter(count)

#自定义tag
class IfKeyEqualNode(Node):
    def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
        self.var1, self.var2 = Variable(var1), Variable(var2)
        self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
        self.negate = negate

    def __repr__(self):
        return "<IfKeyEqualNode>"

    def render(self, context):
        try:
            val1 = self.var1.resolve(context).key()
        except VariableDoesNotExist:
            val1 = None
        try:
            val2 = self.var2.resolve(context).key()
        except VariableDoesNotExist:
            val2 = None
        if (self.negate and val1 != val2) or (not self.negate and val1 == val2):
            return self.nodelist_true.render(context)
        return self.nodelist_false.render(context)

def do_ifkeyequal(parser, token, negate):
    bits = list(token.split_contents())
    if len(bits) != 3:
        raise TemplateSyntaxError, "%r takes two arguments" % bits[0]
    end_tag = 'end' + bits[0]
    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()
    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = NodeList()
    return IfKeyEqualNode(bits[1], bits[2], nodelist_true, nodelist_false, negate)

#@register.tag
def ifkeyequal(parser, token):
    return do_ifkeyequal(parser, token, False)

ifequal = register.tag(ifkeyequal)